<template>
  <div>
    <ContentWrap :show-border="false">
      <SearchBox
        :queryForm="searchList"
        :showExpland="false"
        :show-export="false"
        @query="handleSearchQuery"
      />
    </ContentWrap>
    <ContentWrap :show-border="false">
      <el-button type="primary" @click="handleImport">导入变更状态订单</el-button>
    </ContentWrap>
    <ContentWrap :show-border="false">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="total" label="导入数量" width="180" />
        <el-table-column prop="success" label="成功数量" width="180" />
        <el-table-column prop="fail" label="失败数量" width="180" />
        <el-table-column prop="status" label="订单状态">
          <template #default="{ row }">
            <div class="flex justify-start items-center statusbox">
              <div
                class="px-[7px] py-[2px] flex items-center rounded-[5px]"
                :style="`background-color:${orderStatus[row.status].bgColor}`"
              >
                <div class="w-[12px] h-[12px] rounded-[50%] relative mr-[4px] top-[1px] icon">
                  <img
                    :src="orderStatus[row.status].icon"
                    class="w-full h-full object-contain absolute top-0 left-0"
                  />
                </div>
                <div
                  class="text-[12px] status txt"
                  :style="`color:${orderStatus[row.status].color}`"
                >
                  {{ orderStatus[row.status].name }}
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="createName" label="创建者" />
        <el-table-column prop="createTime" label="创建时间">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="handleDetail(row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNo"
        :total="total"
        @pagination="getList"
      />
    </ContentWrap>
    <Detail ref="detailRef" :row="curRow" />
    <!-- <BatchImport ref="batchImportRef" /> -->
    <BatchImport
      ref="batchImportRef"
      width="40%"
      title="批量变更签收状态"
      titleDesc="使用场景：1.不走合作物流，标记订单结果（已签收/未签收）；2.订单结果错误变更，签收变未签收，未签收变签收"
      :showDot="true"
      :statusList="statusList"
      :showStatusList="true"
      @downTeamplate="downTeamplates"
      @close="isBatchImport = false"
      @confirm="comfirmImport"
    />
  </div>
</template>
<script setup lang="ts">
import type { TradeOrderQueryVO } from '@/api/mall/trade/order'
import Detail from './components/detail.vue'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions, DictDataType } from '@/utils/dict'
import { downTeamplate } from '@/utils'
import * as TradeOrderApi from '@/api/mall/trade/order'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import { formatDate } from '@/utils/formatTime'
import { orderStatus } from '@/utils/order'
import { getUserPage } from '@/api/system/user'
import { getUserPageNew } from '@/api/member/user'

const { loadStart, loadDone } = usePageLoading()

const message = useMessage()

const statusList = getIntDictOptions(DICT_TYPE.ORDER_STATUS)

const detailRef = ref<InstanceType<typeof Detail> | null>(null)

const templateUrl = ref('https://qn-cdn-public.daishubobo.com/orderTempalte.xlsx')

const isBatchImport = ref(false)

const batchImportRef = ref()

const total = ref(0)

const createNameList = ref()

const curRow = ref()

const searchList = ref<TradeOrderQueryVO[]>([
  {
    label: '创建者',
    code: 'userId',
    type: 'select',
    options: createNameList.value
  },

  {
    label: '创建时间',
    code: 'createTime',
    type: 'dateRange'
  }
])

const initQueryParams = {
  pageNo: 1, // 页数
  pageSize: 10, // 每页显示数量
  userId: '',
  createTime: []
}

const queryParams = ref({ ...initQueryParams })

const handleSearchQuery = (val) => {
  /***
   * 搜索框查询条件，目前考虑在查询时 queryParams = {...val,pageNo:1,pageSize:10}
   * */
  queryParams.value = {
    ...initQueryParams,
    ...val
  }
  getList()
}

const tableData = ref([])

/** 查询列表 */
const getList = async () => {
  try {
    const data = await TradeOrderApi.getOrderChangeLogPage(queryParams.value)
    tableData.value = data.list
    total.value = data.total
  } finally {
  }
}

/**
 * 显示导入
 */
const handleImport = () => {
  batchImportRef.value?.show()
}
/**
 * 显示导入详情
 */
const handleDetail = (row) => {
  curRow.value = row
  detailRef.value?.show()
}

/**
 * 下载模板
 */
const downTeamplates = async () => {
  if (!templateUrl.value) {
    message.warning('暂无模板')
    return
  }
  downTeamplate(templateUrl.value, '批量变更签收状态模板.xlsx')
}

/**
 * 导入
 */
const comfirmImport = async (val: any) => {
  try {
    loadStart()
    await TradeOrderApi.importProductOrderStatus(val.file, {
      status: val.statusValue
    })
    message.success('导入成功')
  } finally {
    loadDone()
    getList()
  }
}

//查询部门人员
const getCreateNameList = async () => {
  const res = await getUserPageNew({ pageNo: 1, pageSize: 99 })
  createNameList.value = res.map((item) => {
    return {
      label: item.nickname,
      value: item.id
    }
  })
  searchList.value.map((item) => {
    if (item.code === 'userId') {
      item.options = createNameList.value
    }
  })
}

onMounted(() => {
  getCreateNameList()
  nextTick(() => {
    getList()
  })
})
</script>
<style lang="scss" scoped></style>
